<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>确认订单</p>
    </header>
    <!-- 订单信息部分 -->
    <div class="order-info">
      <h5>订单配送至：</h5>
      <div class="order-info-address" @click="toUserAddress">
        <div class="address-content">
          <!-- 如果有选中的地址就显示选中的地址 -->
          <template v-if="selectedAddress">
            <p class="address-text">{{selectedAddress.address}}</p>
            <p class="contact-info">
              {{selectedAddress.contactName}}
              {{sexFilter(selectedAddress.contactSex)}}
              {{selectedAddress.contactTel}}
            </p>
          </template>
          <!-- 如果有地址列表但没有选中的地址，显示第一个地址 -->
          <template v-else-if="addressList && addressList.length > 0">
            <p class="address-text">{{addressList[0].address}}</p>
            <p class="contact-info">
              {{addressList[0].contactName}}
              {{sexFilter(addressList[0].contactSex)}}
              {{addressList[0].contactTel}}
            </p>
          </template>
          <!-- 如果没有地址，显示提示 -->
          <p v-else class="no-address">请选择送货地址</p>
        </div>
        <i class="fa fa-angle-right"></i>
      </div>
    </div>
    <h3>{{business.businessName}}</h3>
    <!-- 订单明细部分 -->
    <div v-if="cartArr && cartArr.length > 0">
      <ul class="order-detailed">
        <li v-for="item in cartArr" :key="item.foodId">
          <div class="order-detailed-left">
            <img
              :src="item.food.foodImg"
              @error="handleImageError"
              :alt="item.food.foodName"
            >
            <div class="food-info">
              <p class="food-name">{{item.food.foodName}}</p>
              <p class="food-quantity">x {{item.quantity}}</p>
            </div>
          </div>
          <p class="food-price">&#165;{{(item.food.foodPrice * item.quantity).toFixed(2)}}</p>
        </li>
      </ul>
    </div>
    <div v-else class="empty-cart">
      <p>购物车为空</p>
    </div>
    <div class="order-deliveryfee">
      <p>配送费</p>
      <p>&#165;{{(business?.deliveryPrice || 0).toFixed(2)}}</p>
    </div>
    <!-- 合计部分 -->
    <div class="total">
      <div class="total-left">
        &#165;{{totalPrice}}
      </div>
      <div class="total-right" @click="toPayment">
        去支付
      </div>
    </div>
    <div class="cart-right">
      <!-- 不够起送费 -->
      <div class="cart-right-item" 
           v-show="totalSettle < business.starPrice"
           style="background-color: #535356;cursor: default;">
        &#165;{{business.starPrice}}起送
      </div>
      <!-- 达到起送费 -->
      <div class="cart-right-item" 
           v-show="totalSettle >= business.starPrice"
           @click="toOrder">
        去结算
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, onActivated, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { businessApi } from '@/api/business'
import { cartApi } from '@/api/cart'
import { orderApi } from '@/api/order'
import { addressApi } from '@/api/address'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const businessId = ref(route.query.businessId)
const business = ref({
  businessId: '',
  businessName: '',
  deliveryPrice: 0,  // 设置默认配送费
  starPrice: 0
})
const user = ref(null)
const cartArr = ref([])
const deliveryaddress = ref(null)
const defaultImage = ref('') // 设置默认图片路径
const addressList = ref([])
const selectedAddress = ref(null)

// 计算总价
const totalPrice = computed(() => {
  try {
    const foodTotal = cartArr.value.reduce((sum, item) => {
      const price = parseFloat(item.food.foodPrice) || 0
      const quantity = parseInt(item.quantity) || 0
      return sum + (price * quantity)
    }, 0)

    // 使用商家的配送费，添加默认值
    const deliveryPrice = parseFloat(business.value?.deliveryPrice || 0)
    const total = foodTotal + deliveryPrice

    console.log('计算总价:', { foodTotal, deliveryPrice, total })
    return total.toFixed(2)
  } catch (error) {
    console.error('计算总价出错:', error)
    return '0.00'
  }
})

// 加载地址信息
const loadAddress = async () => {
  try {
    if (!user.value?.userName) {
      ElMessage.error('用户信息无效')
      return
    }

    const response = await addressApi.listDeliveryAddressByUserId({
      userName: user.value.userName
    })
    console.log('地址查询响应:', response)

    if (response && response.success) {
      addressList.value = response.data || []

      // 检查本地存储中是否有选中的地址
      const addressKey = `address_${user.value.userName}`
      const savedAddress = localStorage.getItem(addressKey)
      
      if (savedAddress) {
        const parsedAddress = JSON.parse(savedAddress)
        // 从地址列表中找到匹配的地址
        selectedAddress.value = addressList.value.find(addr => 
          addr.daId === parsedAddress.daId
        ) || addressList.value[0]
        
        // 如果找到了地址，更新本地存储
        if (selectedAddress.value) {
          localStorage.setItem(addressKey, JSON.stringify(selectedAddress.value))
        }
      } else if (addressList.value.length > 0) {
        // 如果没有选中的地址，使用第一个地址
        selectedAddress.value = addressList.value[0]
        localStorage.setItem(addressKey, JSON.stringify(selectedAddress.value))
      }
    } else {
      ElMessage.error(response?.message || '加载地址信息失败')
    }
  } catch (error) {
    console.error('加载地址失败:', error)
    ElMessage.error('加载地址信息失败')
  }
}

// 加载购物车项
const loadCartItems = async () => {
  try {
    const response = await cartApi.listCart({
      userName: user.value.userName,
      businessId: business.value.businessId
    })
    console.log('购物车查询响应:', response)

    if (response) {
      const currentBusinessCart = []

      for (const cartItem of response) {
        if (String(cartItem.businessId) === String(businessId.value)) {
          try {
            const foodResponse = await businessApi.getFoodById(cartItem.foodId)
            if (foodResponse) {
              currentBusinessCart.push({
                ...cartItem,
                food: foodResponse,
                quantity: parseInt(cartItem.quantity) || 0
              })
            }
          } catch (error) {
            console.error('获取食品信息失败:', error)
          }
        }
      }

      cartArr.value = currentBusinessCart.filter(item =>
        item.food && item.food.foodPrice && item.quantity > 0
      )
      console.log('当前商家的购物车数据:', cartArr.value)
    }
  } catch (error) {
    console.error('加载购物车失败:', error)
    ElMessage.error('加载购物车信息失败')
  }
}

// 加载商家和购物车信息
const loadBusinessAndCart = async () => {
  try {
    const businessResponse = await businessApi.getBusinessById(businessId.value)
    if (businessResponse) {
      business.value = businessResponse
      console.log('商家信息:', business.value)
    }

    await loadCartItems()
  } catch (error) {
    console.error('加载商家信息失败:', error)
    ElMessage.error('加载商家信息失败')
  }
}

// 跳转到地址选择页面
const toUserAddress = () => {
  router.push({
    path: '/userAddress',
    query: {
      businessId: businessId.value,
      fromOrder: true
    }
  })
}

// 清空购物车
const clearCart = async () => {
  try {
    // 调用后端 removeCart 接口，清空当前商家的所有购物车项
    const response = await cartApi.removeCart({
      userName: user.value.userName,
      businessId: parseInt(businessId.value)
    });
    
    console.log('清空购物车响应:', response);
    
    if (response > 0) {
      // 清空本地购物车数组
      cartArr.value = [];
      console.log('购物车已清空');
    } else {
      throw new Error('清空购物车失败');
    }
  } catch (error) {
    console.error('清空购物车失败:', error);
    ElMessage.warning('购物车商品可能未能成功移除，请稍后重试');
  }
}

// 去支付
const toPayment = async () => {
  try {
    if (!selectedAddress.value) {
      ElMessage.warning('请选择送货地址！')
      return
    }

    if (cartArr.value.length === 0) {
      ElMessage.warning('购物车为空，无法创建订单！')
      return
    }

    // 构造订单数据
    const orderData = {
      userName: user.value.userName,
      businessId: parseInt(businessId.value),
      daId: parseInt(selectedAddress.value.daId),
      orderTotal: parseFloat(totalPrice.value),
      orderState: 0,  // 初始状态
      orderItems: cartArr.value.map(item => ({
        foodId: parseInt(item.foodId),
        quantity: parseInt(item.quantity),
        foodPrice: parseFloat(item.food.foodPrice),
        cartId: item.cartId,  // 添加 cartId 用于后续删除
        food: {
          foodId: item.food.foodId,
          foodName: item.food.foodName,
          foodPrice: item.food.foodPrice,
          foodImg: item.food.foodImg
        }
      }))
    }

    console.log('创建订单参数:', orderData)
    const response = await orderApi.createOrders(orderData)
    console.log('创建订单响应:', response)

    if (response && response.success) {
      const order = response.data
      if (order && order.orderId) {
        // 清空购物车
        await clearCart()
        
        // 跳转到支付页面
        router.push({
          path: '/payment',
          query: { 
            orderId: String(order.orderId),
            amount: String(order.orderTotal)
          }
        })
      } else {
        ElMessage.error('创建订单失败：未获取到订单信息')
      }
    } else {
      ElMessage.error(response?.message || '创建订单失败')
    }
  } catch (error) {
    console.error('创建订单错误:', error)
    ElMessage.error('创建订单时发生错误，请稍后重试！')
  }
}

const handleImageError = (e) => {
  e.target.src = defaultImage.value
}

onMounted(async () => {
  const userStr = sessionStorage.getItem('user')
  if (!userStr) {
    router.push('/login')
    return
  }
  
  user.value = JSON.parse(userStr)
  console.log('当前用户信息:', user.value)
  console.log('获取到商家ID:', businessId.value)

  await loadAddress()
  await loadBusinessAndCart()
})

onActivated(async () => {
  if (user.value) {
    await loadAddress()  // 每次激活组件时重新加载地址
  }
})

// 添加性别过滤器函数
const sexFilter = (value) => {
  return value === 1 ? '先生' : '女士'
}

// 监听地址变化
watch(() => route.query, async () => {
    if (route.query.fromAddress) {
        await loadAddress()  // 重新加载地址信息
    }
}, { deep: true })

// 在模板中使用
defineExpose({
  sexFilter
})
</script>
<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}
/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
/****************** 订单信息部分 ******************/
.wrapper .order-info {
  /*注意这里，不设置高，靠内容撑开。因为地址有可能折行*/
  width: 100%;
  margin-top: 12vw;
  background-color: #0097EF;
  box-sizing: border-box;
  padding: 2vw;
  color: #fff;
}
.wrapper .order-info h5 {
  font-size: 5vw;
  font-weight: 600;
  margin-bottom: 1vw;
  color: rgba(255, 255, 255, 0.95);
}
.wrapper .order-info .order-info-address {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vw 0;
}
.wrapper .order-info .address-content {
  flex: 1;
  margin-right: 3vw;
}
.wrapper .order-info .address-text {
  font-size: 4.5vw;
  font-weight: 500;
  margin-bottom: 1.5vw;
  word-break: break-all;
}
.wrapper .order-info .contact-info {
  font-size: 3.8vw;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 1.5vw;
}
.wrapper .order-info .no-address {
  font-size: 5.5vw;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  padding: 3vw 0;
  text-align: center;
}
.wrapper .order-info .fa-angle-right {
  font-size: 5vw;
  color: rgba(255, 255, 255, 0.8);
}
.wrapper .order-info p {
  font-size: 3vw;
}
.wrapper h3 {
  box-sizing: border-box;
  padding: 3vw;
  font-size: 4vw;
  color: #666;
  border-bottom: solid 1px #DDD;
}
/****************** 订单明细部分 ******************/
.wrapper .order-detailed {
  width: 100%;
}
.wrapper .order-detailed li {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .order-detailed li .order-detailed-left {
  display: flex;
  align-items: center;
}
.wrapper .order-detailed li .order-detailed-left img {
  width: 10vw;
  height: 10vw;
}
.wrapper .order-detailed li .order-detailed-left .food-info {
  margin-left: 3vw;
}
.wrapper .order-detailed li .order-detailed-left .food-name {
  font-size: 3.8vw;
  color: #333;
  margin-bottom: 1vw;
}
.wrapper .order-detailed li .order-detailed-left .food-quantity {
  font-size: 3.2vw;
  color: #666;
}
.wrapper .order-detailed li .food-price {
  font-size: 3.8vw;
  color: #f60;
  font-weight: 500;
}
.wrapper .order-deliveryfee {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;
}
/****************** 订单合计部分 ******************/
.wrapper .total {
  width: 100%;
  height: 14vw;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
}
.wrapper .total .total-left {
  flex: 2;
  background-color: #505051;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .total .total-right {
  flex: 1;
  background-color: #38CA73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}
.empty-cart {
  width: 100%;
  padding: 40px 20px;
  text-align: center;
  color: #999;
  background: #f8f8f8;
  font-size: 4vw;
}
.user-info {
  font-size: 3.2vw;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 1vw;
}
</style>
